package com.vf.admin.client.controller;

import cn.hutool.core.util.ObjectUtil;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.service.*;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.vf.admin.utils.StringEx.isNull;

/**
 * 房间送礼，1对1送礼
 *
 * @author anxiang
 * @version 1.0.0
 * @ClassName AppSongliController.java
 * @Description TODO
 * @createTime 2021年11月06日 17:39:00
 */
@CrossOrigin
@Controller
@RequestMapping("/app/songli")
public class AppSongliController extends ClientBaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    AppMingXiShouLiService appMingXiShouLiService;
    @Autowired
    AppMingxiMeilizhiService appMingxiMeilizhiService;
    @Autowired
    AppMingxiJinbiService appMingxiJinbiService;
    @Autowired
    AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    AppGiftNumService appGiftNumService;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppGiftService appGiftService;
    @Autowired
    AppKnapsackService appKnapsackService;
    @Autowired
    AppFansClubService appFansClubService;
    @Autowired
    AppRoomService appRoomService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private AppDailyTasController appDailyTasController;

    /**
     * 直播房间送礼
     *
     * @Param: [roomid 房间id, userid 被送礼用户id, giftid 礼物id,  giftnumid 礼物数量id]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/06/06
     * @Time: 17:45
     */
    @RequestMapping("/roomsl")
    @ResponseBody
    public Result roomsongli(Integer roomid, String userid, Integer giftid, Integer giftnumid) {
        try {


            if (isNull(roomid)) {
                return this.errorJSON("房间id不能为空");
            }
            if (isNull(userid)) {
                return this.errorJSON("被送礼用户id不能为空");
            }
            AppRoom room = appRoomService.getById(roomid);
            if (room == null) {
                return this.errorJSON("房间不存在");
            }
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            if (isNull(giftid)) {
                return this.errorJSON("礼物id不能为空");
            }
            AppGift gift = appGiftService.get(giftid);
            if (gift == null) {
                return this.errorJSON("礼物信息不存在");
            }
            //如果是贵族礼物
            if (gift.getLiwuguishu() == 2) {
                if(user.getIsguizu() == 2 || user.getNobleid() < 4) {
                    return this.errorJSON("您还不是贵族或者未达到指定等级，无法赠送专属礼物");
                }
            }
            if (isNull(giftnumid)) {
                return this.errorJSON("礼物数量不能为空");
            }
            AppGiftNum giftNum = appGiftNumService.get(giftnumid);
            if (giftNum == null) {
                return this.errorJSON("礼物数量信息不存在");
            }
            String[] str = userid.split(",");
            String userIds = "";
            for (String s : str) {
                if (!isNull(s)) {
                    userIds += "," + s;
                }
            }
            if (!isNull(userIds)) {
                userIds = userIds.substring(1);
            }
            if (isNull(userIds)) {
                return this.errorJSON("被送礼用户id不能为空");
            }
            List<AppUser> userList = appUserService.getPiliangTengxuncodeByUser(userIds);

            if (userList.size() != str.length) {
                return this.errorJSON("送礼人不存在");
            }
            for (AppUser appUser : userList) {
                if (appUser.getId().equals(user.getId())) {
                    return this.errorJSON("不能给自己赠送礼物");
                }
            }
            //计算出礼物总金额
            BigDecimal giftmoney = new BigDecimal(String.valueOf(gift.getGoldmoney() * giftNum.getNum()));
            //计算出送所有用户消耗的金额
            BigDecimal m = giftmoney.multiply(new BigDecimal(str.length));
            if (gift.getGoumaifangshi() == Constants.goumaifangshi_jinbi) {
                if (m.compareTo(user.getJinbi()) > 0) {
                    return this.errorJSON("金币余额不足");
                }
            } else if (gift.getGoumaifangshi() == Constants.goumaifangshi_zuanshi) {
                if (m.compareTo(user.getDiamonds()) > 0) {
                    return this.errorJSON("钻石余额不足");
                }
            }

            boolean flag = appGiftService.roomGift(str, user, giftmoney, gift, giftNum, room);
            if (flag) {
                AppUser user2 = appUserService.get(userId);
                Map<String, Object> tomap = new HashMap<>(16);
                tomap.put("diamonds", user2.getDiamonds().subtract(giftmoney));
                tomap.put("jinbi", user2.getJinbi().subtract(giftmoney));
                tomap.put("meili", user2.getCharmvalue());
                return this.sucessJSON(tomap, "送礼成功");
            } else {
                return this.errorJSON("送礼失败");
            }
        } catch (Exception e) {
            logger.error("房间内送礼异常", e);
            return this.errorJSON("系统繁忙");
        }
    }


    /**
     * 1对1送礼
     *
     * @Param: [userid 送礼人id, giftid 礼物id, giftnumid 礼物数量id]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/07/6
     * @Time: 18:48
     */
    @RequestMapping("/songli")
    @ResponseBody
    public Result songli(Integer userid, Integer giftid, Integer giftnumid) {
        try {
            if (isNull(userid)) {
                return this.errorJSON("送礼人id不能为空");
            }
            if (isNull(giftid)) {
                return this.errorJSON("礼物id不能为空");
            }
            if (isNull(giftnumid)) {
                return this.errorJSON("礼物数量id不能为空");
            }
            AppUser sluser = appUserService.getTcOrId(userid);
            if (sluser == null) {
                return this.errorJSON("送礼人不存在");
            }
            AppGift gift = appGiftService.get(giftid);
            if (gift == null) {
                return this.errorJSON("礼物信息不存在");
            }
            //如果是贵族礼物
            if (gift.getLiwuguishu() == 2) {
                AppUser user = appUserService.get(getUserId());
                if(user.getIsguizu() == 2 || user.getNobleid() < 2) {
                    return this.errorJSON("您还不是贵族或者未达到指定等级，无法赠送专属礼物");
                }
            }
            AppGiftNum giftNum = appGiftNumService.get(giftnumid);
            if (giftNum == null) {
                return this.errorJSON("礼物数量信息不存在");
            }
            //计算礼物金额
            BigDecimal money = new BigDecimal(String.valueOf(gift.getGoldmoney() * giftNum.getNum()));
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            if (user.getId().equals(sluser.getId())) {
                return this.errorJSON("不能给自己赠送礼物");
            }
            //判断金额是否够
            if (gift.getGoumaifangshi() == Constants.goumaifangshi_zuanshi) {
                //钻石
                if (money.compareTo(user.getDiamonds()) > 0) {
                    return this.errorJSON("钻石余额不足");
                }
            } else if (gift.getGoumaifangshi() == Constants.goumaifangshi_jinbi) {
                //金币
                if (money.compareTo(user.getJinbi()) > 0) {
                    return this.errorJSON("金币余额不足");
                }
            }
            boolean flag = appGiftService.userGift(sluser, user, new BigDecimal(String.valueOf(money)), gift, giftNum);
            if (flag) {
                return this.sucessJSON("送礼成功");
            } else {
                return this.errorJSON("送礼失败");
            }
        } catch (Exception e) {
            logger.error("1对1送礼异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

    @RequestMapping("/songlinum")
    @ResponseBody
    public Result songlinum(Integer userid, Integer giftid, Integer giftnum) {
        try {
            if (isNull(userid)) {
                return this.errorJSON("送礼人id不能为空");
            }
            if (isNull(giftid)) {
                return this.errorJSON("礼物id不能为空");
            }
            AppUser sluser = appUserService.getTcOrId(userid);
            if (sluser == null) {
                return this.errorJSON("送礼人不存在");
            }
            AppGift gift = appGiftService.get(giftid);
            if (gift == null) {
                return this.errorJSON("礼物信息不存在");
            }
            //如果是贵族礼物
            if (gift.getLiwuguishu() == 2) {
                AppUser user = appUserService.get(getUserId());
                if(user.getIsguizu() == 2 || user.getNobleid() < 4) {
                    return this.errorJSON("您还不是贵族或者未达到指定等级，无法赠送专属礼物");
                }
            }
            //计算礼物金额
            BigDecimal money = new BigDecimal(String.valueOf(gift.getGoldmoney() * giftnum));
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            if (user.getId().equals(sluser.getId())) {
                return this.errorJSON("不能给自己赠送礼物");
            }
            //判断金额是否够
            if (gift.getGoumaifangshi() == Constants.goumaifangshi_zuanshi) {
                //钻石
                if (money.compareTo(user.getDiamonds()) > 0) {
                    return this.errorJSON("钻石余额不足");
                }
            } else if (gift.getGoumaifangshi() == Constants.goumaifangshi_jinbi) {
                //金币
                if (money.compareTo(user.getJinbi()) > 0) {
                    return this.errorJSON("金币余额不足");
                }
            }
            boolean flag = appGiftService.userGiftNum(sluser, user, new BigDecimal(String.valueOf(money)), gift, giftnum);
            if (flag) {
                return this.sucessJSON("送礼成功");
            } else {
                return this.errorJSON("送礼失败");
            }
        } catch (Exception e) {
            logger.error("1对1送礼异常", e);
            return this.errorJSON("系统繁忙");
        }
    }


    /**
     * 心动赠送礼物
     *
     * @param userid 被心动人id
     * @return
     */
    @RequestMapping("/beckoningGift")
    @ResponseBody
    public Result beckoningGift(Integer userid) {
        Integer giftnumid = 1;
        if (isNull(userid)) {
            return this.errorJSON("请指定心动人");
        }
        AppUser sluser = appUserService.get(userid);
        if (sluser == null) {
            return this.errorJSON("用户不存在");
        }

        //获取最新数据
        Integer nowUserId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser user = appUserService.get(nowUserId);
        if(ObjectUtil.isNull(user)){
            return this.errorJSON("用户没有登录！");
        }
        if (user.getId().equals(sluser.getId())) {
            return this.errorJSON("不能给自己赠送礼物");
        }
        if (user.getDiamonds().compareTo(BigDecimal.ZERO) == 0) {
            return this.errorJSON("钻石余额不足");
        }
        AppGift gift = appGiftService.randomGift(user.getDiamonds());
        if (gift == null) {
            return this.errorJSON("钻石余额不足,请充值后心动聊天");
        }
        //计算礼物金额
        BigDecimal money = new BigDecimal(String.valueOf(gift.getGoldmoney() * 1));

        //判断金额是否够
        if (gift.getGoumaifangshi() == Constants.goumaifangshi_zuanshi) {
            //钻石
            if (money.compareTo(user.getDiamonds()) > 0) {
                return this.errorJSON("钻石余额不足");
            }
        } else if (gift.getGoumaifangshi() == Constants.goumaifangshi_jinbi) {
            //金币
            if (money.compareTo(user.getJinbi()) > 0) {
                return this.errorJSON("金币数量不足");
            }
        } else {
            return errorJSON("礼物类型错误");
        }
        boolean flag = appGiftService.beckoningUserGift(sluser, user, money, gift);
        if (flag) {
            if(user.getSex() != sluser.getSex()) {
                appDailyTasController.getAwardEveryDay(getUserId(), ClientConstants.TaskEveryDay.HEART_BEAT);
            }
            return this.sucessJSON(gift, "成功");
        } else {
            return this.errorJSON("错误");
        }
    }


    /**
     * 1对1背包送礼
     *
     * @Param: [userid 送礼人id, giftid 礼物id, giftnumid 礼物数量id]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/07/6
     * @Time: 18:48
     */
//    @RequestMapping("/beibaosongli")
    @ResponseBody
    public Result beibaosongli(Integer userid, Integer beibaoid, Integer giftnumid) {
        try {
            if (isNull(userid)) {
                return this.errorJSON("送礼人id不能为空");
            }
            if (isNull(beibaoid)) {
                return this.errorJSON("背包礼物id不能为空");
            }
            if (isNull(giftnumid)) {
                return this.errorJSON("礼物数量id不能为空");
            }
            AppUser sluser = appUserService.getTcOrId(userid);
            if (sluser == null) {
                return this.errorJSON("送礼人不存在");
            }
            AppKnapsack knapsack = appKnapsackService.get(beibaoid);
            if (knapsack == null) {
                return this.errorJSON("背包礼物不存在");
            }
            if (knapsack.getLiwushuliang() <= 0) {
                return this.errorJSON("礼物数量不足");
            }
            AppGiftNum giftNum = appGiftNumService.get(giftnumid);
            if (giftNum == null) {
                return this.errorJSON("礼物数量信息不存在");
            }
            AppGift gift = appGiftService.get(knapsack.getGifid());
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            if (user.getId().equals(sluser.getId())) {
                return this.errorJSON("不能给自己赠送礼物");
            }
            //判断数量是否够
            if (giftNum.getNum() > knapsack.getLiwushuliang()) {
                return this.errorJSON("礼物数量不足");
            }
            //送礼
            boolean flag = appGiftService.userBeibaoGift(sluser, user, knapsack, gift, giftNum);
            if (flag) {
                return this.sucessJSON("送礼成功");
            } else {
                return this.errorJSON("送礼失败");
            }
        } catch (Exception e) {
            logger.error("1对1送礼异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

}
